import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import {
  type Menu,
  getMenuList,
  addMenu,
  updateMenu,
  deleteMenu
} from "@/api/system";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import { IconifyIconOnline } from "@/components/ReIcon";
import { DictTag } from "@/components/ReDict";

export function useMenu() {
  const form = reactive({
    title: null,
    state: null
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);

  const columns: TableColumnList = [
    {
      label: "菜单名称",
      prop: "title",
      width: 150
    },
    {
      label: "图标",
      prop: "icon",
      width: 60,
      cellRenderer: ({ row }) => (
        <IconifyIconOnline icon={row.icon} width={"35px"} height={"35px"} />
      )
    },
    {
      label: "路径",
      prop: "path"
    },
    {
      label: "组件",
      prop: "component"
    },
    {
      label: "组件名称",
      prop: "name",
      width: 150
    },
    {
      label: "排序",
      prop: "sort",
      minWidth: 60
    },
    {
      label: "状态",
      prop: "state",
      minWidth: 60,
      cellRenderer: ({ row, props }) => (
        <DictTag size={props.size} value={row.state} code="State" />
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ];

  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function onSearch() {
    loading.value = true;
    getMenuList(form)
      .then(data => {
        dataList.value = handleTree(data); // 处理成树结构
      })
      .catch(err => {
        message(`菜单查询失败:${err.message}`, {
          type: "error"
        });
      })
      .finally(() => {
        setTimeout(() => {
          loading.value = false;
        }, 500);
      });
  }

  function openDialog(title = "新增", row?: Menu) {
    addDialog({
      title: `${title}菜单`,
      props: {
        formInline: {
          id: row?.id ?? "",
          parentId: row?.parentId ?? "",
          path: row?.path ?? "",
          component: row?.component ?? "",
          title: row?.title ?? "",
          name: row?.name ?? "",
          icon: row?.icon ?? "",
          frameSrc: row?.frameSrc ?? "",
          state: row?.state ?? true,
          sort: row?.sort ?? 1,
          showLink: row?.showLink ?? false,
          keepAlive: row?.keepAlive ?? false,
          type: row?.type ?? "MENU_TYPE_FOLDER"
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as Menu;
        function add() {
          addMenu(curData)
            .then(() => {
              message("菜单新增成功", {
                type: "success"
              });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`菜单新增失败:${err}`, {
                type: "error"
              });
            });
        }
        function update() {
          updateMenu(curData)
            .then(() => {
              message("菜单更新成功", { type: "success" });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`菜单更新失败:${err}`, { type: "error" });
            });
        }
        FormRef.validate((valid: boolean) => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              add();
            } else {
              // 实际开发先调用编辑接口，再进行下面操作
              update();
            }
          }
        });
      }
    });
  }

  function handleDelete(row: Menu) {
    if (!row.isLeaf) {
      message("请先删除所有子菜单后再删除上级菜单", { type: "warning" });
      return;
    }
    deleteMenu(row.id)
      .then(() => {
        message("菜单删除成功", { type: "success" });
        onSearch();
      })
      .catch(err => {
        message(`菜单删除失败:${err}`, { type: "error" });
      });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、编辑菜单 */
    openDialog,
    /** 删除菜单 */
    handleDelete
  };
}
